﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Windows.Forms;

using ImageRecognition2.Forms;

using LowLevelGraphics;
using LowLevelGraphics.Filter;

namespace ImageRecognition2.Action
{
    /// <summary>
    /// Action Cut From Mask
    /// </summary>
    public class ActionCutFromMask : AbstractCommand
    {
        /// <summary>
        /// Default constructor
        /// </summary>
        public ActionCutFromMask()
        {
        }

        internal ActionCutFromMask(ActionCutFromMask _ActionCutFromMask)
        {
        }

        /// <summary>
        /// Executes this filter
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public override void Run(object sender, EventArgs e)
        {
            Image mainFormSingletonActivePictureBoxBackgroundImage = MainFormSingleton.ActivePictureBox.BackgroundImage;
            FormChildList childList = new FormChildList();
            if (childList.ShowDialog() != DialogResult.OK) return;

            FormItem item = childList.FormItem;
            if (item == null) return;

            Image image = item.Form.pictureBox1.BackgroundImage;

            if (image == mainFormSingletonActivePictureBoxBackgroundImage)
            {
                MessageBox.Show("Please choose different pictures", "Result");
                return;
            }

            UnsafeBitmap bitmapSource = mainFormSingletonActivePictureBoxBackgroundImage;
            UnsafeBitmap imageSource = image;

            new PerPixelFilter(new PerPixelFilter.PerPixelFilterDelegateTwoSources(
                delegate(Color color1, Color color2) 
                {
                    return color2 != Definitions.White ? Definitions.Black : color1; 
                }
                )).Process(bitmapSource, imageSource);

            imageSource.Dispose();
            bitmapSource.Dispose();

            MainFormSingleton.ActivePictureBox.BackgroundImage = bitmapSource.InternalBitmap;
            MainFormSingleton.ActivePictureBox.Invalidate();
        }

        public override object Clone()
        {
            return new ActionCutFromMask(this);
        }
    }
}
